package com.liu.webstore.service.impl;

import com.liu.webstore.entity.DiscussPost;
import com.liu.webstore.entity.User;
import com.liu.webstore.repository.DiscussPostMapper;
import com.liu.webstore.repository.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @Author LiuYumei
 * @Date 2022/7/25 21:52
 */
@Service
public class DemoServiceImpl {
    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DiscussPostMapper discussPostMapper;

    /**
     * 编程式事务
     */
    public Object demoTransaction() {
        transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        return transactionTemplate.execute((TransactionCallback<Object>) transactionStatus -> {
            // 代码业务逻辑
            User user = new User();
            user.setUsername("lisi");
            userMapper.insertUser(user);
            int count = 1/0;
            DiscussPost discussPost = new DiscussPost();
            discussPost.setUserId(user.getId());
            discussPost.setTitle("公告");
            discussPostMapper.insertDiscussPost(discussPost);
            return transactionStatus;
        });
    }
}
